import {useEffect, useRef, useState} from "react";
import './App.css';
import _ from "lodash";
import classnames from 'classnames'
import { v4 as uuidv4 } from 'uuid';
import dayjs from "dayjs";
import Father from "./state";

const tabs = [
    {'name': '最新', 'id': 'time'},
    {'name': '热门', 'id': 'hot'},
]

const list = [
    {'id': '1', 'name': '张三', 'content': '张三的留言', 'time': '2022-01-01', 'hot': 70},
    {'id': '2', 'name': '李四', 'content': '李四的留言', 'time': '2022-02-02', 'hot': 100},
    {'id': '3', 'name': '王五', 'content': '王五的留言', 'time': '2021-01-03', 'hot': 200},
    {'id': '4', 'name': '赵六', 'content': '赵六的留言', 'time': '2022-01-04', 'hot': 400},
]

function App() {
    const [data, setData] = useState(list)
    const [type, setTyp] = useState('time')
    const [comment, setComment] = useState('')
    const inputRef = useRef(null)
    const handleChange = (type) => {
        setTyp(type)
        if (type === 'time') {
            setData(_.orderBy(list, ['time'], ['desc']))
        } else {
            setData(_.orderBy(list, ['hot'], ['desc']))

        }
    }
    const handleCommentChange = (e) => {
        setComment(e.target.value)
    }

    const handleSubmit = () => {
        setData([...data, {'id': uuidv4(), 'name': '匿名用户', 'content': comment, 'time': dayjs().format('YYYY-MM-DD'), 'hot': 110}])
        setComment('')
        inputRef.current.focus()
    }

    useEffect(() => {
        handleChange('time');
    }, []);

    return (
        <div>
            <div>
                <input type="text" value={comment} ref={inputRef}
                       onChange={ handleCommentChange }
                />
                <button onClick={ handleSubmit }>发布</button>
            </div>
            <div>
                {
                    tabs.map(e => <span key={e.id} className={classnames({'active-tab': type === e.id})}
                                        onClick={() => handleChange(e.id)}>{e.name}</span>)
                }
            </div>
            <ul>
                {
                    data.map(e => <li key={e.id}>{e.name} {e.content} {e.hot} {e.time}</li>)
                }
            </ul>
            <p>父子组件通信</p>
            <Father></Father>
        </div>
    );
}

export default App;
